package com.itheima.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.entity.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Result result = new Result(false, "登录失败，密码错误");
        String message = exception.getMessage();
        if (!message.equals("Bad credentials")){
            result.setMessage(message);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("text/html;charset=utf-8");
        objectMapper.writeValue(response.getOutputStream(),result);
    }
}
